<?php
defined('BASEPATH') OR exit('No direct script access allowed');

// 后台通用方法
class Api extends BaseController {

	public function __construct() {
        parent::__construct();
    }

    // 获取班牌首页信息
    public function get_class_data($brandId = 0){
        // 加载数据库类
        $this->load->model('classesModel');
        $this->load->model('schoolModel');
        $this->load->model('contentModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        // 获取班级信息
        $classInfo = $this->classesModel->get_class_info($brandInfo['class_id']);
        // 获取学校信息
        $schoolInfo = $this->schoolModel->get_school_info($classInfo['school_id']);
        // 获取班主任信息
        $masterInfo = $this->schoolModel->get_teacher_info($classInfo['class_master']);
        
        // 获取教师列表
        $teacherParams['schoolId'] = $classInfo['school_id'];
        // 过滤软删除
        $teacherParams['isDelete'] = 0;
        $teacherList = $this->schoolModel->get_teacher_list($teacherParams);
        $teacherList = array_value_to_key($teacherList, 'id');
        // 获取课程表设置
        $scheduleArray = $lessonArray = array();
        $scheduleParams['schoolId'] = $classInfo['school_id'];
        $scheduleList = $this->classesModel->get_school_schedule($scheduleParams);
        foreach($scheduleList as $schedule) {
            $weekLesson = array();

            $scheduleSetting = json_decode($schedule['schedule_time_json'], true);
            $scheduleSetting = array_value_to_key($scheduleSetting, 'timeslotInDay');
            // 生成全部课程时间点
            for($i = 1; $i <= $schedule['schedule_week_days']; $i ++) {
                foreach($scheduleSetting as $lessonTime) {
                    $lsData['weekIndex'] = $i;
                    $lsData['classIndex'] = $lessonTime['timeslotInDay'];
                    $lsData['startTime'] = $lessonTime['beginTime'];
                    $lsData['endTime'] = date("H:i", strtotime($lessonTime['beginTime']) + $lessonTime['duration'] * 60);
                    $lsData['lessonName'] = $lsData['teacherName'] = $lsData['teacherId'] = '';

                    $lessonKey = $i. $lsData['classIndex'];
                    $weekLesson[$lessonKey] = $lsData;
                }
            }
            
            // 获取课程表课程
            $lessonParams['scheduleId'] = $schedule['id'];
            $lessonParams['classId'] = $classInfo['id'];
            $lessonList = $this->classesModel->get_school_schedule_lesson($lessonParams);
            foreach($lessonList as $lesson) {
                $classLesson = $lesson['schedule_lesson'];
                // 写入课程名称
                $lessonKey = $lesson['schedule_week_index']. $lesson['schedule_class_index'];
                $weekLesson[$lessonKey]['lessonName'] = $classLesson;
                $weekLesson[$lessonKey]['teacherId'] = $teacherList[$lesson['schedule_teacher']]['id'];
                $weekLesson[$lessonKey]['teacherName'] = $teacherList[$lesson['schedule_teacher']]['realname'];
                // 获取班级科目
                if(!in_array($classLesson, $lessonArray)) $lessonArray[] = $classLesson;
            }

            // 检查是本周还是下周课程
            $weekLesson = array_values($weekLesson);
            if($schedule['schedule_this_week']) {
                $scheduleArray['thisWeek']['lesson'] = $weekLesson;
            } else {
                $scheduleArray['nextWeek']['lesson'] = $weekLesson;
            }
        }

        // 班级相册，首页推荐
        $albumParams['classId'] = $classInfo['id'];
        $albumParams['recommend'] = 1;
        $albumList = $this->contentModel->get_album($albumParams);
        $albumArray = array();
        foreach($albumList as $image) {
            $albumArray[] = array(
                "imageLink" => $image['image_link'],
                "imageDesc" => $image['image_desc']
            );
        }
        // 获取天气预报编码
        $areaInfo = $this->schoolModel->get_area_info($schoolInfo['school_area']);
        $cityJson = file_get_contents(APPLICATION_FOLDER. DIRECTORY_SEPARATOR . "data". DIRECTORY_SEPARATOR. "_city.json");
        $cityData = array_value_to_key(json_decode($cityJson, true), 'city_name');
        $weatherId = isset($cityData[$areaInfo['area_name']]) ? $cityData[$areaInfo['area_name']]['city_code'] : 0;
        // 返回值
        $ret['className'] = $classInfo['class_name'];
        $ret['classImg'] = UP_URL. "default/class.jpg";
        // 班级格言
        $ret['classSlogan'] = $classInfo['class_slogan'];
        // 班级口号
        $ret['classWord'] = $classInfo['class_word'];
        $ret['classContent'] = $classInfo['class_content'];
        $ret['weatherId'] = $weatherId;
        // 班主任
        $ret['classMaster'] = null;
        if(!empty($masterInfo)) {
            $ret['classMaster'] = array(
                "id" => $masterInfo['id'],
                "name" => $masterInfo['realname'],
                "headimgurl" => $masterInfo['headimgurl'],
                "mobile" => $masterInfo['mobile'],
                "message" => $masterInfo['content']
            );
        }
        // 班级课程
        $ret['classLesson'] = $lessonArray;
        // 首页推荐图片
        $ret['albumList'] = $albumArray;
        // 课程信息
        $ret['schedule'] = $scheduleArray;
        // 本月之星
        $ret['classStar'] = '';
        if (null !== $classInfo['class_star']) {
            $student = $this->schoolModel->get_student_info($classInfo['class_star']);
            if (isset($student['realname'])) {
                $ret['classStar'] = $student['realname'];
            } 
        }  
        // 班牌管理密码
        $ret['brandPassword'] = $brandInfo['brand_password'];
        // 班牌开关机时间
        $ret['brandPowerTime'] = json_decode($brandInfo['power_time'], true);
        // 是否启用人脸识别功能
        $ret['brandFaceDetect'] = intval($schoolInfo['school_face_detect']);
		// 相机缩放倍数
        $ret['cameraZoom'] = floatval($brandInfo['brand_camera_zoom']);
        
        exit(json("", true, $ret));
    }

    // 获取班级通知列表
    public function get_class_notify_data($brandId, $page = 1){
        // 加载数据库类
        $this->load->model('classesModel');
        $this->load->model('contentModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        // 获取班级信息
        $classInfo = $this->classesModel->get_class_info($brandInfo['class_id']);
        // 获取数据条数
        $totalParams['isDelete'] = 0;
        $totalParams['classId'] = $classInfo['id'];
        $totalParams['getRowNumber'] = true;
        $total = $this->contentModel->get_notify_list($totalParams);
        // 获取数据
        $data['isDelete'] = 0;
        $data['classId'] = $classInfo['id'];
        $data['pageStart'] = ($page - 1) * ADMIN_PAGE_SIZE;
        $data['pageSize']= ADMIN_PAGE_SIZE;
        $notifyData = array();
        $notifyList = $this->contentModel->get_notify_list($data);
        foreach($notifyList as $notify) {
            $notifyData[] = array(
                "id" => $notify['id'],
                "title" => $notify['notify_title'],
                "content" => urlencode($notify['notify_content']),
                "time" => $notify['createtime']
            );
        }
        // 返回值
        $ret['total'] = $total;
        $ret['data'] = $notifyData;
        exit(json("", true, $ret));
    }

    // 获取班级通知详情
    public function get_class_notify_info($brandId, $notifyId){
        // 加载数据库类
        $this->load->model('classesModel');
        $this->load->model('contentModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));

        // 获取通知详情
        $notifyInfo = $this->contentModel->get_notify_info($notifyId);
        if(!$notifyInfo) throw new Exception("内容不存在");
        // 返回值
        $ret['id'] = $notifyInfo['id'];
        $ret['title'] = $notifyInfo['notify_title'];
        $ret['content'] = urlencode($notifyInfo['notify_content']);
        $ret['endtime'] = $notifyInfo['urgent_endtime'];
        exit(json("", true, $ret));
    }

    // 获取班级动态列表
    public function get_class_news_data($brandId, $page = 1){
        // 加载数据库类
        $this->load->model('classesModel');
        $this->load->model('contentModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        // 获取班级信息
        $classInfo = $this->classesModel->get_class_info($brandInfo['class_id']);
        // 获取数据条数
        $totalParams['isDelete'] = 0;
        $totalParams['classId'] = $classInfo['id'];
        $totalParams['getRowNumber'] = true;
        $total = $this->contentModel->get_news_list($totalParams);
        // 获取数据
        $data['isDelete'] = 0;
        $data['classId'] = $classInfo['id'];
        $data['pageStart'] = ($page - 1) * ADMIN_PAGE_SIZE;
        $data['pageSize']= ADMIN_PAGE_SIZE;    
        $newsData = array();
        $newsList = $this->contentModel->get_news_list($data);
        foreach($newsList as $news) {
            $newsData[] = array(
                "id" => $news['id'],
                "cover" => get_img_link_from_text($news['news_content']),
                "title" => $news['news_title'],
                "content" => urlencode($news['news_content']),
                "time" => $news['createtime']
            );
        }
        // 返回值
        $ret['total'] = $total;
        $ret['data'] = $newsData;
        exit(json("", true, $ret));
    }

    // 获取校园公告列表
    public function get_class_announce_data($brandId, $page = 1){
        // 加载数据库类
        $this->load->model('classesModel');
        $this->load->model('contentModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        // 获取班级信息
        $classInfo = $this->classesModel->get_class_info($brandInfo['class_id']);
        // 获取数据条数
        $totalParams['isDelete'] = 0;
        $totalParams['schoolId'] = $classInfo['school_id'];
        $totalParams['getRowNumber'] = true;
        $total = $this->contentModel->get_announce_list($totalParams);
        // 获取数据
        $data['isDelete'] = 0;
        $data['schoolId'] = $classInfo['school_id'];
        $data['pageStart'] = ($page - 1) * ADMIN_PAGE_SIZE;
        $data['pageSize']= ADMIN_PAGE_SIZE;
        $announceData = array();
        $announceList = $this->contentModel->get_announce_list($data);
        foreach($announceList as $announce) {
            $announceData[] = array(
                "id" => $announce['id'],
                "title" => $announce['announce_title'],
                "content" => urlencode($announce['announce_content']),
                "time" => $announce['createtime']
            );
        }
        // 返回值
        $ret['total'] = $total;
        $ret['data'] = $announceData;
        exit(json("", true, $ret));
    }

    // 获取班级作业列表
    public function get_class_homework_data($brandId, $page = 1){
        // 加载数据库类
        $this->load->model('classesModel');
        $this->load->model('schoolModel');
        $this->load->model('contentModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        // 获取班级信息
        $classInfo = $this->classesModel->get_class_info($brandInfo['class_id']);
        // 获取数据条数
        $totalParams['isDelete'] = 0;
        $totalParams['classId'] = $classInfo['id'];
        $totalParams['getRowNumber'] = true;
        $total = $this->contentModel->get_homework_list($totalParams);
        // 获取科目列表
        $lessonParams['schoolId'] = $classInfo['school_id'];
        $lessonList = $this->schoolModel->get_lesson_list($lessonParams);
        $lessonList = array_value_to_key($lessonList, "id");

        // 获取数据
        $data['isDelete'] = 0;
        $data['classId'] = $classInfo['id'];
        $data['pageStart'] = ($page - 1) * ADMIN_PAGE_SIZE;
        $data['pageSize']= ADMIN_PAGE_SIZE;
        $homeworkData = array();
        $homeworkList = $this->contentModel->get_homework_list($data);
        foreach($homeworkList as $homework) {
            $homeworkData[] = array(
                "id" => $homework['id'],
                "title" => $homework['homework_title'],
                "content" => urlencode($homework['homework_content']),
                "time" => $homework['createtime'],
                "lesson" => $homework['lesson_id'] ? $lessonList[$homework['lesson_id']]['lesson_name'] : ''
            );
        }
        // 返回值
        $ret['total'] = $total;
        $ret['data'] = $homeworkData;
        exit(json("", true, $ret));
    }

    // 获取班级视频
    public function get_class_video_data($brandId){
        // 加载数据库类
        $this->load->model('classesModel');
        $this->load->model('contentModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        // 获取班级信息
        $classInfo = $this->classesModel->get_class_info($brandInfo['class_id']);
        // 获取数据条数
        $totalParams['getRowNumber'] = true;
        $totalParams['isDelete'] = 0;
        $total = $this->contentModel->get_video_list($totalParams);
        // 获取数据
        // $data['pageStart'] = ($page - 1) * ADMIN_PAGE_SIZE;
        // $data['pageSize']= ADMIN_PAGE_SIZE;
        $data['classId'] = $classInfo['id'];
        $videoData = array();
        $videoList = $this->contentModel->get_video_list($data);
        foreach($videoList as $video) {
            $videoData[] = array(
                "title" => $video['video_title'],
                "link" => $video['video_link'],
                "poster"=> $video['video_poster'],
                "time" => $video['createtime']
            );
        }
        // 返回值
        $ret['total'] = $total;
        $ret['data'] = $videoData;
        exit(json("", true, $ret));
    }

    // 获取班级相册
    public function get_class_album_data($brandId){
        // 加载数据库类
        $this->load->model('classesModel');
        $this->load->model('contentModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        // 获取班级信息
        $classInfo = $this->classesModel->get_class_info($brandInfo['class_id']);
        // 获取相册分类
        $albumData = array();
        $params['classId'] = $classInfo['id'];
        $albumCategory = $this->contentModel->get_album_category($params);
        // 获取相册内容
        foreach($albumCategory as $category) {
            $albumImage = array();
            // 获取相册内容
            $albumParams['categoryId'] = $category['id'];
            $albumImages = $this->contentModel->get_album($albumParams);
            foreach($albumImages as $image) {
                $albumImage['category'] = $category['album_category_name'];
                $albumImage['item'][] = array(
                    "title" => $image['image_desc'],
                    "link" => $image['image_link']
                );
            }
            $albumData[] = $albumImage;
        }
        // 返回值
        exit(json("", true, $albumData));
    }

    // 获取班级荣誉
    public function get_class_honor_data($brandId){
        // 加载数据库类
        $this->load->model('classesModel');
        $this->load->model('contentModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        // 获取班级信息
        $classInfo = $this->classesModel->get_class_info($brandInfo['class_id']);
        // 获取相册分类
        $albumData = array();
        $params['classId'] = -1;
        $albumCategory = $this->contentModel->get_album_category($params);
        // 获取相册内容
        foreach($albumCategory as $category) {
            $albumImage = array();
            // 获取相册内容
            $albumParams['classId'] = $classInfo['id'];
            $albumParams['categoryId'] = $category['id'];
            $albumImages = $this->contentModel->get_album($albumParams);
            foreach($albumImages as $image) {
                $albumImage[] = array(
                    "title" => $image['image_desc'],
                    "link" => $image['image_link']
                );
            }
            $albumData = $albumImage;
        }
        // 返回值
        exit(json("", true, $albumData));
    }

    // 获取教师风采(教师列表)
    public function get_class_teacher_list($brandId){
        // 加载数据库类
        $this->load->model('schoolModel');
        $this->load->model('classesModel');
        $this->load->model('contentModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        // 获取班级信息
        $classInfo = $this->classesModel->get_class_info($brandInfo['class_id']);
        // 获取教师列表
        $teacherArray = array();
        $teacherParams['schoolId'] = $classInfo['school_id'];
        $teacherParams['isDelete'] = 0;
        $teacherList = $this->schoolModel->get_teacher_list($teacherParams);
        $teacherList = array_value_to_key($teacherList, 'id');
        // 获取班级课程表
        $lessonParams['classId'] = $classInfo['id'];
        $lessonList = $this->classesModel->get_school_schedule_lesson($lessonParams);
        foreach($lessonList as $lesson) {
            // 获取课程老师信息
            $teacherInfo = $teacherList[$lesson['schedule_teacher']];
            $teacherArray[$teacherInfo['id']] = array(
                "id" => $teacherInfo['id'],
                "name" => $teacherInfo['realname'],
                "lesson" => $lesson['schedule_lesson'],
                "headimgurl" => $teacherInfo['headimgurl'],
                "desc" => urlencode($teacherInfo['content'])
            );
        }
        sort($teacherArray);
        exit(json("", true, $teacherArray));
    }

    // 获取学生列表
    public function get_class_student_list($brandId){
        // 加载数据库类
        $this->load->model('schoolModel');
        $this->load->model('classesModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        // 获取班级信息
        $classInfo = $this->classesModel->get_class_info($brandInfo['class_id']);
        // 获取班级学生人数
        $studentArray = array();
        $studentParams['classId'] = $classInfo['id'];
        $studentParams['isDelete'] = 0;
        $studentList = $this->schoolModel->get_student_list($studentParams);
        foreach($studentList as $key => $student) {
            $studentArray[] = array(
                "id" => $student['id'],
                "name" => $student['realname'],
                "headimgurl" => $student['gender'] == '男' ? UP_URL. "default/boy.jpg" : UP_URL. "default/girl.jpg",
                "job" => $student['job'],
                "cardnum" => $student['realcard'],
                "faceImage" => $student['face_image']
            );
        }
        exit(json("", true, $studentArray));
    }

    // 更新学生头像
    public function update_student_face_image($brandId){
        // 加载数据库类
        $this->load->model('schoolModel');
        $this->load->model('classesModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        // 获取学生信息
        $cardNum = $this->post("cardnum");
        if(!$cardNum) throw new Exception("更新失败，请录入学生卡号后重试"); 
        $studentInfo = $this->schoolModel->get_student_info_by_realcard($cardNum, $brandInfo['school_id']);
        if(!$studentInfo) throw new Exception("更新失败，参数错误");
        // 获取图片base64值
        $imageBase64 = $this->post("student_face_image", false);
        $imageType = get_img_type_from_base64($imageBase64);
        if(!$imageType) throw new Exception("更新失败，图片参数错误");
        // 写入图片
        require_once('vendor/autoload.php');
        $fileName = date("Y"). "/". date("m"). "/". date("d"). "/". time(). ".". $imageType;
        $serviceConfig = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
        $client = new Upyun\Upyun($serviceConfig);
        $result = $client->write("/". $fileName, file_get_contents($imageBase64));   // 上传图片，自动创建目录
        if(!isset($result['x-upyun-width'])) throw new Exception("更新失败，图片参数错误");
        // 更新图片
        $update['face_image'] = UP_URL. $fileName;
        $this->db->update(SchoolModel::$schoolStudentTable, $update, "id='{$studentInfo['id']}'");
        exit(json("", true));
    }


    // 获取APP版本
    public function get_app_version($brandId){
        // 获取系统配置类
        $this->load->model('configModel');
        $this->load->model('classesModel');
        $this->load->model('schoolModel');

        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) throw new Exception("参数错误");
        // 获取班级信息
        $schoolInfo = $this->schoolModel->get_school_info($brandInfo['school_id']);
        if(!$schoolInfo) throw new Exception("参数错误");

        // 获取版本号
        $versionName = $this->configModel->get_config_info('app_version', true);
        $versionCode = intval($this->configModel->get_config_info('app_version_code', true));
        // 如果关闭班牌更新
        if(!$schoolInfo['school_brand_update']) {
            $versionName = "0.0.0";
            $versionCode = 0;
        }

        $ret['version'] = $versionName;
        $ret['versionCode'] = $versionCode;
        $ret['app'] = $this->configModel->get_config_info('app_link', true);
        exit(json("", true, $ret));
    }

    // 根据地区编码，获取下级地区列表
    public function get_area_list($areaCode){
        // 加载数据库类
        $this->load->model('schoolModel');
        $areaInfo = $this->schoolModel->get_area_info($areaCode);
        // 获取城市列表
        $areaParams['parentId'] = $areaInfo['id'];
        $areaList = $this->schoolModel->get_area_list($areaParams);
        exit(json("", true, $areaList));
    }

    // 学生刷卡签到接口
    public function student_sign($brandId){
        // 加载数据库类
        $this->load->model('schoolModel');
        $this->load->model('classesModel');
        // 签到类型
        $signType = $this->post("sign_type") ? $this->post("sign_type") : SIGN_CARD_CLASS;
        // 签到图片
        $imageBase64 = $this->post("sign_image", false);
        $imageType = get_img_type_from_base64($imageBase64);
        if(!$imageType) throw new Exception("签到失败，图片参数错误");
        // 签到时间
        $signTime = $this->post("sign_time");
        if(!$signTime) throw new Exception("签到失败，签到时间不能为空");

        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) throw new Exception("签到失败，参数错误");
        // 如果有传课程ID，则根据当前课程获取班级信息
        $courseId = $this->post("course_id") ? $this->post("course_id") : 0;
        if(!$courseId) throw new Exception("签到失败，参数错误");

        if($courseId) {
            $courseInfo = $this->classesModel->get_sch_lesson($courseId);
            $classInfo = $this->classesModel->get_class_info($courseInfo['class_id']); 
        } else {
            // 获取班级信息
            $classInfo = $this->classesModel->get_class_info($brandInfo['class_id']);
        }
        if(!$classInfo) throw new Exception("签到失败，参数错误");
        
        // 如果是刷卡签到，获取学生信息
        if($signType == SIGN_CARD_CLASS) {
            $realcard = $this->post("cardnum");
            $studentInfo = $this->schoolModel->get_student_info_by_realcard($realcard, $brandInfo['school_id']);
        }
        // 如果是人脸签到，获取学生信息
        if($signType == SIGN_FACE_CLASS) {
            $studentId = $this->post('student_id');
            $studentInfo = $this->schoolModel->get_student_info($studentId);    
        }
        if(!$studentInfo) throw new Exception("签到失败，无效的卡号");
        // 获取兴趣班id
        $teachClassArray = explode(",", $studentInfo['teaching_class_id']);
        if($studentInfo['class_id'] != $classInfo['id'] && !in_array($classInfo['id'], $teachClassArray)) throw new Exception("签到失败，无效的卡号");
        // 检查今天是否已签到
        // $todaySign = $this->classesModel->get_today_sign($studentInfo['id'], $classInfo['id']);
        // if($todaySign) throw new Exception("你今天已经签到，无需重复签到");
        // 写入图片
        require_once('vendor/autoload.php');
        $fileName = date("Y"). "/". date("m"). "/". date("d"). "/". time(). ".". $imageType;
        $serviceConfig = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
        $client = new Upyun\Upyun($serviceConfig);
        $result = $client->write("/". $fileName, file_get_contents($imageBase64));   // 上传图片，自动创建目录
        // 写文件上传调试日志
        if(!isset($result['x-upyun-width'])) throw new Exception("更新失败，图片参数错误");

        // 入库，做个毛线逻辑
        $insert['school_id'] = $classInfo['school_id'];
        $insert['class_id'] = $classInfo['id'];
        $insert['course_id'] = $courseId;
        $insert['student_id'] = $studentInfo['id'];
        $insert['student_card_number'] = $studentInfo['realcard'];
        $insert['brand_id'] = $brandInfo['id'];
        $insert['sign_type'] = $signType;
        $insert['sign_img'] = UP_URL. $fileName;
        $insert['sign_date'] = date("Y-m-d", strtotime($signTime));
        $insert['createtime'] = date("Y-m-d H:i:s", strtotime($signTime));
        $this->db->insert(ClassesModel::$signTable, $insert);
        // 返回值
        $ret['name'] = $studentInfo['realname'];
        $ret['signId'] = $this->db->insert_id();
        exit(json("", true, $ret));
    }

    // 这个接口废弃了
    // 这个接口废弃了
    // 这个接口废弃了
    // 学生刷卡签到图片更新接口
    public function update_student_sign_image($brandId){
        // 加载数据库类
        $this->load->model('classesModel');
        // 获取学生信息
        $signId = $this->post("id");
        $signInfo = $this->classesModel->get_sign_info($signId);
        if(!$signInfo) throw new Exception("更新失败，无效的id");
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) throw new Exception("更新失败，参数错误");
        // 获取班级信息
        if($signInfo['brand_id'] != $brandInfo['id']) throw new Exception("更新失败，参数错误");
        // 获取图片base64值
        $imageBase64 = $this->post("image", false);
        $imageType = get_img_type_from_base64($imageBase64);
        if(!$imageType) throw new Exception("更新失败，图片参数错误");
        // 写入图片
        require_once('vendor/autoload.php');
        $fileName = date("Y"). "/". date("m"). "/". date("d"). "/". time(). ".". $imageType;
        $serviceConfig = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
        $client = new Upyun\Upyun($serviceConfig);
        $result = $client->write("/". $fileName, file_get_contents($imageBase64));   // 上传图片，自动创建目录

        // 写文件上传调试日志
        if(!isset($result['x-upyun-width'])) throw new Exception("更新失败，图片参数错误");
        // 入库，做个毛线逻辑
        $update['sign_img'] = UP_URL. $fileName;
        $this->db->update(ClassesModel::$signTable, $update, "id='{$signId}'");
        // 返回值
        $ret['image'] = $update['sign_img'];
        exit(json("", true, $ret));
    }

    // 学生考勤接口
    public function get_student_sign_data($brandId){
        // 加载数据库类
        $this->load->model('classesModel');
        $this->load->model('dataModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) throw new Exception("无效的班牌id");

        // 如果有传课程ID，则根据当前课程获取班级信息
        $courseId = $this->get("course_id") ? $this->get("course_id") : 0;
        if($courseId) {
            $courseInfo = $this->classesModel->get_sch_lesson($courseId);
            $classInfo = $this->classesModel->get_class_info($courseInfo['class_id']); 
        } else {
            // 获取班级信息
            $classInfo = $this->classesModel->get_class_info($brandInfo['class_id']);
        }
        if(!$classInfo) throw new Exception("无效的班牌id");
        // 获取学生考勤信息
        $today = date("Y-m-d");
        $isTeachingClass = $classInfo['id'] != $brandInfo['class_id'];
        $studentList = $this->dataModel->get_sign_data($classInfo, $today, $isTeachingClass);
        // 检查用户签到情况
        $signArray = array(
            "sign" => array(),
            "noSign" => array(),
            "leave" => array()
        );
        foreach($studentList as $student) {
            $studentData = array(
                // "id" => $student['id'],
                "id" => $student['sign_id'],
                "studentId" => $student['id'],
                "studentCard" => $student['realcard'],
                "name" => $student['realname'],
                "image" => $student['sign_img']. "!small",
                "signTime" => $student['signTime'] ? date("H时i分", strtotime($student['signTime'])) : '',
                "faceImage" => $student['face_image'],
                "headimgurl" => $student['gender'] == '男' ? UP_URL. "default/boy.jpg" : UP_URL. "default/girl.jpg"
            );
            if($student['sign_id']) {
                $signArray['sign'][] = $studentData;
            } else {
                $signArray['noSign'][] = $studentData;
            }
        }
        exit(json("", true, $signArray));
    }

    // socket通知
    public function alert_socket(){
        $toChannel = str_replace(CHANNEL_ID_PREFIX, "", $this->post("to"));
        $contentType = $this->post("type");
        $content = $this->post("msg", false);

        // 如果是屏幕截图
        if($contentType == CONTENT_TYPE_SCREENSHOT) {
            // 获取图片base64值
            $imageType = get_img_type_from_base64($content);
            if(!$imageType) throw new Exception("更新失败，图片参数错误");
            // 写入图片
            require_once('vendor/autoload.php');
            $fileName = date("Y"). "/". date("m"). "/". date("d"). "/". time(). ".". $imageType;
            $serviceConfig = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
            $client = new Upyun\Upyun($serviceConfig);
            $result = $client->write("/". $fileName, file_get_contents($content));   // 上传图片，自动创建目录
            if(!isset($result['x-upyun-width'])) throw new Exception("更新失败，图片参数错误");

            $content = UP_URL. $fileName;
        }

        // socket值
        $socketData['type'] = $contentType;
        $socketData['content'] = $content;

        // 推送消息到客户端
        $this->load->library('socket');
        $this->socket->send_sae_channel_msg($toChannel, $socketData);

        exit(json("", true));
    }

    // 检查当前课程信息
    public function get_current_course($brandId){
        // 加载数据库类
        $this->load->model('classesModel');
        $this->load->model('schoolModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        // 获取班级信息
        $classInfo = $this->classesModel->get_class_info($brandInfo['class_id']);
        if(!$classInfo) exit(json("不存在的班级", false));
        // 获取本周课程
        $schedule = $this->classesModel->get_campus_schedule($classInfo['campus_id']);
        $timeJson = json_decode($schedule['schedule_time_json'], true);
        // 获取当前时间
        $currentTime = $this->post('time') ? $this->post('time') : date("H:i");
        // 当前课程节数
        $courseIndex = 0;
        $courseStartTime = $courseEndTime = "";

        // 获取当前时间是第几节课
        foreach($timeJson as $timePoint) {
            $classStart = date("H:i", strtotime($timePoint['beginTime']. "-10 minutes"));                       // 课程开始时间
            $classEnd = date("H:i", strtotime($timePoint['beginTime']. "+{$timePoint['duration']} minutes"));   // 课程结束时间

            // if($classStart <= $currentTime && $classEnd > $currentTime) {
            if($currentTime > $classStart && $currentTime <= $classEnd) {
                $courseIndex = $timePoint['timeslotInDay'];
                $courseStartTime = $timePoint['beginTime'];
                $courseEndTime = $classEnd;
            }
        }
        // 获取本周指定课程信息
        $weekIndex = date("w",time());
        $weekIndex = $weekIndex ? $weekIndex : 7;       // 如果是0的话，就是周日，需要替换成7
        // 获取本次上课信息
        $scheduleLesson = $this->classesModel->get_schedule_lesson_info($schedule['id'], $weekIndex, $courseIndex, $classInfo['classroom_id']);
        if(!$courseIndex || !$scheduleLesson) exit(json("没有对应课程"));

        // 获取教师信息
        $teacherInfo = $this->schoolModel->get_teacher_info($scheduleLesson['schedule_teacher']);
        // 获取当前班级信息
        $courseClassInfo = $this->classesModel->get_class_info($scheduleLesson['class_id']);
        // 返回课程信息
        $ret['courseId'] = $scheduleLesson['id'];
        $ret['startTime'] = $courseStartTime;
        $ret['endTime'] = $courseEndTime;
        $ret['className'] = $courseClassInfo['class_name'];
        $ret['lessonName'] = $scheduleLesson['schedule_lesson'];
        $ret['teacherName'] = $teacherInfo['realname'];
        $ret['teacherHeadimgurl'] = $teacherInfo['headimgurl'];

        exit(json("", true, $ret));
    }

    // 获取班牌今天所有的人脸数据
    public function get_brand_face_data($brandId){
        // 加载数据库类
        $this->load->model('classesModel');
        $this->load->model('schoolModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        // 获取班牌绑定的班级
        $classInfo = $this->classesModel->get_class_info($brandInfo['class_id']);
        if(!$classInfo) exit(json("不存在的班级", false));
        // 获取校区ID
        $campusId = $classInfo['campus_id'];
        // 获取课室id
        $classroomId = $classInfo['classroom_id'];
        // 获取本周课程表
        $scheduleInfo = $this->classesModel->get_campus_schedule($campusId);
        // 获取本周所有课程
        $weekIndex = date("w",time());
        $params['weekIndex'] = $weekIndex ? $weekIndex : 7;
        $params['scheduleId'] = $scheduleInfo['id'];
        $params['classroom'] = $classroomId;
        $lessonList = $this->classesModel->get_school_schedule_lesson($params);
        // 获取所有班级
        $classArray = array();
        foreach ($lessonList as $lesson) if(!in_array($lesson['class_id'], $classArray)) $classArray[] = $lesson['class_id'];
        //  获取班级所有学生
        $stuParams['classORteach'] = implode(",", $classArray);
        $stuParams['isDelete'] = 0;
        $studentList = $this->schoolModel->get_student_list($stuParams);
        // 返回值
        $ret = array();
        foreach($studentList as $student) {
            $data['studentId'] = $student['id'];
            $data['studentName'] = $student['realname'];
            $data['faceImage'] = $student['face_image'];
            $ret[] = $data;
        }

        exit(json("", true, $ret));
    }

    // 获取学生课表
    public function get_student_personal_data(){
        // 加载数据库类
        $this->load->model('schoolModel');
        $this->load->model('classesModel');
        // 如果是传学生ID
        if($this->get("student_id")) {
            $studentId = $this->get("student_id");
            $studentInfo = $this->schoolModel->get_student_info($studentId);    
        }
        // 如果是传学生卡号
        if($this->get("cardnum")) {
            $realcard = $this->get("cardnum");
            $studentInfo = $this->schoolModel->get_student_info_by_realcard($realcard);
        }
        if(!$studentInfo) throw new Exception("接口错误，不存在的学生ID");
        // 获取班级信息
        $classInfo = $this->classesModel->get_class_info($studentInfo['class_id']);

        // 获取教师列表
        $teacherArray = array();
        $teacherParams['schoolId'] = $studentInfo['school_id'];
        $teacherParams['isDelete'] = 0;
        $teacherList = $this->schoolModel->get_teacher_list($teacherParams);
        $teacherList = array_value_to_key($teacherList, 'id');
        // 获取本周课表设置
        $scheduleInfo = $this->classesModel->get_campus_schedule($studentInfo['campus_id']);

        // 解析json字符串
        $weekLesson = array();
        $scheduleSetting = json_decode($scheduleInfo['schedule_time_json'], true);
        if(!empty($scheduleSetting)){
            $scheduleSetting = array_value_to_key($scheduleSetting, 'timeslotInDay');
            // 生成全部课程时间点
            for($i = 1; $i <= $scheduleInfo['schedule_week_days']; $i ++) {
                foreach($scheduleSetting as $lessonTime) {
                    $lsData['weekIndex'] = $i;
                    $lsData['classIndex'] = $lessonTime['timeslotInDay'];
                    $lsData['startTime'] = $lessonTime['beginTime'];
                    $lsData['endTime'] = date("H:i", strtotime($lessonTime['beginTime']) + $lessonTime['duration'] * 60);
                    $lsData['lessonName'] = $lsData['teacherName'] = $lsData['teacherId'] = '';
    
                    $lessonKey = $i. $lsData['classIndex'];
                    $weekLesson[$lessonKey] = $lsData;
                }
            }
        }
        
        // 获取课程表课程
        $lessonParams['scheduleId'] = $scheduleInfo['id'];
        // 获取班级集合
        $classArray = array_merge(explode(",", $studentInfo['class_id']), explode(",", $studentInfo['teaching_class_id']));
        $lessonParams['classSet'] = trim(implode(",", $classArray), ",");
        $lessonList = $this->classesModel->get_school_schedule_lesson($lessonParams);
        foreach($lessonList as $lesson) {
            $classLesson = $lesson['schedule_lesson'];
            // 写入课程名称
            $lessonKey = $lesson['schedule_week_index']. $lesson['schedule_class_index'];
            $weekLesson[$lessonKey]['lessonName'] = $classLesson;
            $weekLesson[$lessonKey]['teacherId'] = $teacherList[$lesson['schedule_teacher']]['id'];
            $weekLesson[$lessonKey]['teacherName'] = $teacherList[$lesson['schedule_teacher']]['realname'];
        }
        sort($weekLesson);

        $ret['lesson'] = $weekLesson;
        $ret['name'] = $studentInfo['realname'];
        $ret['headimgurl'] = $studentInfo['gender'] == '男' ? UP_URL. "default/boy.jpg" : UP_URL. "default/girl.jpg";
        $ret['className'] = $classInfo['class_name'];

        exit(json("", true, $ret));
    }
}
